package controller

import (
	"gin/common"
	"gin/response"
	"gin/service"
	"gin/validate"
	"github.com/gin-gonic/gin"
)

func RoleSelect(ctx *gin.Context) {
	var selectDictQuery validate.SelectRoleQuery

	err := ctx.ShouldBindJSON(&selectDictQuery)

	if err != nil {
		response.Fail(ctx, nil, err.Error())
		return
	}

	selectQueryParam := common.GenerateSelectQueryParam(selectDictQuery.Param, "log")

	total, resData, queryErr := service.SelectRole(&selectQueryParam)

	if queryErr != nil {
		// 查询失败
		response.Fail(ctx, nil, queryErr.Error())
	} else {
		// 查询成功
		response.Success(ctx, gin.H{"data": gin.H{"total": total, "rows": resData}}, "success")
	}
}

// 查询单条词库
func RoleFind(ctx *gin.Context) {
	var selectDictQuery validate.SelectRoleQuery

	err := ctx.ShouldBindJSON(&selectDictQuery)

	if err != nil {
		response.Fail(ctx, nil, err.Error())
		return
	}

	selectQueryParam := common.GenerateSelectQueryParam(selectDictQuery.Param, "log")

	resData, queryErr := service.FindRole(selectQueryParam)

	if queryErr != nil {
		// 查询失败
		response.Fail(ctx, nil, queryErr.Error())
	} else {
		// 查询成功
		response.Success(ctx, gin.H{"data": resData}, "success")
	}
}

// 插入日志
func RoleCreate(ctx *gin.Context) {
	var addRole validate.AddRoleWrapper

	err := ctx.ShouldBindJSON(&addRole)

	if err != nil {
		response.Fail(ctx, nil, err.Error())
		return
	}

	resData, createErr := service.CreateRole(addRole.Data)
	if createErr != nil {
		// 插入失败
		response.Fail(ctx, nil, createErr.Error())
		return
	}

	response.Success(ctx, gin.H{"data": resData}, "success")
}

func RoleUpdate(ctx *gin.Context) {
	var updateRole validate.UpdateRoleWrapper

	err := ctx.ShouldBindJSON(&updateRole)

	if err != nil {
		response.Fail(ctx, nil, err.Error())
		return
	}

	resData, createErr := service.UpdateRole(updateRole.Data)
	if createErr != nil {
		// 插入失败
		response.Fail(ctx, nil, createErr.Error())
		return
	}

	response.Success(ctx, gin.H{"data": resData}, "success")
}

func RoleDelete(ctx *gin.Context) {
	var deleteRoleParam validate.DeleteRoleParam

	err := ctx.ShouldBindJSON(&deleteRoleParam)

	if err != nil {
		response.Fail(ctx, nil, err.Error())
		return
	}

	selectQueryParam := common.GenerateFilterParam(&deleteRoleParam.Param, "sentence")

	service.DeleteRole(&selectQueryParam)

	// 查询成功
	response.Success(ctx, nil, "success")

}
